<template>
    <div>
        <vxe-toolbar custom ref="toolbarRef">
            <template #buttons>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="handleAdd"
                        v-if="this.editable"
                >
                    新 增
                </el-button>
            </template>
            <template #tools>

                <el-tooltip content="清空筛选" placement="top">
                    <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
                </el-tooltip>

                <vxe-button icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle
                            style="margin-right: 12px;"></vxe-button>
            </template>
        </vxe-toolbar>
        <vxe-grid
                v-bind="gridOptions"
                ref="tableRef"
                show-footer
                class="mytable-scrollbar"
                :data="list"
                :edit-rules="validRules"
                :tooltip-config="{ zIndex: 9999 }"
                :customConfig="customConfig"
                :menu-config="menuConfig"
                :footer-method="footerMethod"
                :edit-config="{
                trigger: 'click',
                mode: 'row',
                showUpdateStatus: true,
                showInsertStatus: true,
                beforeEditMethod:beforeEdit}"
                @edit-closed="editClosedEvent"
                @edit-actived="editActivedEvent"
                @menu-click="contextMenuClickEvent">

            <template #aboutNo_header>
                {{tableHeader.aboutNoHeader}}
            </template>
            <template #aboutItem_header>
                {{tableHeader.aboutItemHeader}}
            </template>

<!--            <template #price_edit="scope">-->
<!--                <vxe-input v-model="scope.row.price" type="float" digits="5"  max="99999999" :controls="false"  @change="(value)=>calTotalPrice(value.value,scope.row.num,scope)"-->
<!--                ></vxe-input>-->
<!--            </template>-->
            <template #num_edit="scope">
                <vxe-input v-model="scope.row.num" type="integer" max="99999999" min="0" :controls="false"
                           @blur="(value)=>checkNum(scope.row.num, scope.row)"
                           @change="(value)=>calTotalPrice(scope.row.price,value.value,scope)"
                ></vxe-input>
            </template>

            <template #unit_edit="scope">
                <el-select v-model="scope.row.unit"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择单位"

                           type="string" transfer>
                    <!--          @change="handleSelectPackUnit"-->
                    <el-option
                            v-for="item in packUnitDic"
                            :key="item.name"
                            :value="item.name"
                            :label="item.name+' - '+item.type"/>
                </el-select>
            </template>
            <template #labelColor_edit="scope">
                <!--<vxe-input v-model="row.tabNo" type="text"></vxe-input>-->
                <el-select v-model="scope.row.labelColor"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择箱唛颜色"
                           type="string" transfer>
                    <el-option
                            v-for="item in labelColorDic"
                            :key="item.dictValue"
                            :value="item.dictValue"
                            :label="item.dictValue"/>
                </el-select>
            </template>

            <template #packSpec_edit="scope">
                <vxe-input v-model="scope.row.packSpec" ></vxe-input>
            </template>

            <template #packCtnNum_edit="scope">
                <vxe-input v-model="scope.row.packCtnNum" type="integer" min="0" max="99999999" :controls="false"
                ></vxe-input>
                <!--@blur="(value)=>checkNum(scope.row.num, scope.row)"-->
                <!--@change="(value)=>calTotalNum(scope.row.price,value.value,scope)"-->

            </template>
<!--            <template #packUnit_edit="scope">-->
<!--                <el-select v-model="scope.row.packUnit"-->
<!--                           :clearable="true"-->
<!--                           :filterable="true"-->
<!--                           placeholder="请选择包装单位"-->

<!--                           type="string" transfer>-->
<!--                    &lt;!&ndash;          @change="handleSelectPackUnit"&ndash;&gt;-->
<!--                    <el-option-->
<!--                            v-for="item in packUnitDic"-->
<!--                            :key="item.name"-->
<!--                            :value="item.name"-->
<!--                            :label="item.name+' - '+item.type"/>-->
<!--                </el-select>-->
<!--            </template>-->

            <template #qcNo_edit="scope">
                <vxe-input v-model="scope.row.qcNo" :controls="false"></vxe-input>
            </template>

            <template #btn_default="{ row }">
                <template v-if="!isActiveStatus(row) && this.editable">
                    <!--<el-tooltip content="修改" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleUpdate(row)"-->
                    <!--&gt;修改-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                    <el-tooltip content="查看QC信息" placement="top">
                        <el-button
                                icon="el-icon-view"
                                link
                                size="small"
                                type="primary"
                                @click="handleOpenQC(row)"
                        ></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top" v-if="!row.outItemId">
                        <el-button
                                icon="el-icon-delete"
                                link
                                size="small"
                                type="primary"
                                @click="handleDelete(row)"
                        ></el-button>
                    </el-tooltip>
                </template>
                <template v-else>
                </template>
            </template>
        </vxe-grid>
        <select-order-item ref="selectOrderItemRef" @setOrderItemList="setOrderItemList"></select-order-item>
        <select-prod-item ref="selectProdItemRef" @setProdItemList="setProdItemList"></select-prod-item>
        <select-purchase-item ref="selectPurchaseItemRef" @setPurchaseItemList="setPurchaseItemList"></select-purchase-item>
        <select-material ref="selectMaterial" @setMaterial="setMaterial"></select-material>
    </div>
</template>

<script>
    import {findList,overflowNum} from "@/api/anwise/stock/stock_in_item";
    import {generateQCSign} from "@/api/common";
    import {mapGetters} from "vuex";
    import {VXETable} from 'vxe-table'
    import {getDictionary} from "@/api/system/dictbiz";
    import {select as unitSelect} from "@/api/anwise/unit_info";
    import {Pattern} from "@/utils/validate.js";
    import {select as supplierSelect} from "@/api/anwise/supplier";
    import selectOrderItem from './select_order_item.vue';
    import selectProdItem from './select_prod_item.vue';
    import selectMaterial from './select_material.vue';
    import selectPurchaseItem from './select_purchase_item.vue';
    import {markRaw} from "vue";


    export default {
        components: {
            selectOrderItem,
            selectProdItem,
            selectMaterial,
            selectPurchaseItem
        },
        props: {
            // 入仓类型
            inType: {
                type: String,
                default: "",
            },
            fromDept: {
                type: String,
                default: "",
            },
            fromNo:{
                type: String,
                default: "",
            },
            fromName:{
                type: String,
                default: "",
            },
            isRole:{
                type: String,
                default:"",
            },
            toDept:{
                type: String,
                default:"",
            }
        },
        data() {
            return {
                idNo: '',
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                editRow: {},
                labelColorDic:[],
                rowIndex: '',
                box: false,
                isEdit: false,
                iconSearch: true,
                searchShow: false,
                editable: true,
                list: [],
                customConfig: {
                    storage: true,
                    checkMethod({column}) {
                        if (['facName'].includes(column.field)) {
                            return false
                        }
                        return true
                    },
                },
                menuConfig: {},
                form: {},
                query: {},
                loading: true,
                data: [],
                selectionList: [],
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                subVisible: false,
                direction: 'rtl',
                customerName: "安伟客户表",
                customerTypeList: [],
                tableHeader: {
                    aboutNoHeader: "",
                    aboutItemHeader: "",
                },
                packUnitDic: [],
                nameOptions: [{data: null}],
                validRules: {
                    unit: [
                        {required: true, message: '单位必须填写'}
                    ],
                    num: [
                        {required: true, message: '数量必须填写'}
                    ],
                },
                gridOptions: {
                    height: '400px',
                    border: true,
                    showOverflow: true,
                    keepSource: true,
                    size: "medium",
                    rowConfig: {
                        // keyField: 'id',
                        isHover: true
                    },
                    columnConfig: {
                        resizable: true
                    },
                    // editRules: ,
                    columns: [
                        // {type: 'checkbox', width: 50, fixed:'left', visible: true},
                        // {type: 'seq', width: 50, fixed:'left', align: "center"},
                        // {
                        //     title: "入仓单号",
                        //     field: "idNo",
                        //     minWidth: 120,
                        // },
                        {
                            title: "项",
                            field: "itemNo",
                            minWidth: 120,
                        },
                        {
                            title: "相关单号",
                            field: "aboutNo",
                            minWidth: 120,
                            slots: {header: 'aboutNo_header'},
                        },
                        {
                            title: "相关项",
                            field: "aboutItem",
                            minWidth: 120,
                            slots: {header: 'aboutItem_header'},
                        },
                        {
                            title: "订单编号",
                            field: "orderIdNo",
                            minWidth: 120,
                        },
                        {
                            title: "物料编号",
                            field: "materialNo",
                            minWidth: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "客户条码",
                            field: "barCode",
                            minWidth: 120,
                        },
                        {
                            title: "物料名称",
                            field: "materialName",
                            minWidth: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "规格",
                            field: "specification",
                            minWidth: 120,
                        },
                        {
                            title: "单位",
                            field: "unit",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'unit_edit'}
                        },
                        {
                            title: "数量",
                            field: "num",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'num_edit'}
                        },
                        // {
                        //     title: "单价",
                        //     field: "price",
                        //     minWidth: 120,
                        //     editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                        //     slots: {edit: 'price_edit'}
                        // },
                        // {
                        //     title: "金额",
                        //     field: "totalPrice",
                        //     minWidth: 120,
                        // },
                        {
                            title: "包装规格",
                            field: "packSpec",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'packSpec_edit'}
                        },
                        {
                            title: "包装箱数",
                            field: "packCtnNum",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'packCtnNum_edit'}
                        },
                        {
                            title: "交货地点",
                            field: "deliAddr",
                            width: 200,
                        },
                        {
                            title: "备注",
                            field: "remark",
                            minWidth: 230,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                        },
                        {
                            title: "箱唛",
                            field: "packLabel",
                            minWidth: 350,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                        },
                        {
                            title: "箱唛颜色",
                            field: "labelColor",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'labelColor_edit'}
                        },
                        {
                            title: "QC编号",
                            field: "qcNo",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'qcNo_edit'}
                        },
                        {
                            field: 'btn',
                            title: '操作',
                            minWidth: 120,
                            align: "center",
                            fixed: "right",
                            visible: true,
                            slots: {default: 'btn_default'}
                        }
                    ]
                },
                supplierDic: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.stock_in_item_add, false),
                    viewBtn: this.validData(this.permission.stock_in_item_view, false),
                    delBtn: this.validData(this.permission.stock_in_item_delete, false),
                    editBtn: this.validData(this.permission.stock_in_item_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
        },
        watch: {
            'inType'() {
                this.changeByInType();
            },
            'fromNo'(){
                this.changeByFromNo();
            }
        },
        mounted() {
            console.log('this.intype',this.inType);
            this.isEdit = false;
            this.disabledCommit(false);
            this.init();
            this.$nextTick(() => {
                this.$refs.tableRef.connect(this.$refs.toolbarRef);
            })
        },
        methods: {
            handleOpenQC(row) {
                if (row.qcNo) {
                    generateQCSign().then(res => {
                        console.log("res", res);
                        if (res.data.success) {
                            if (this.inType === "生产入仓") {
                                window.open("https://www.agop.com.cn/pc/views/qc/final_inspection/final_inspection_show.html?INSP_NO=" + row.qcNo + "&sign=" + res.data.data.sign + "&timestamp=" + res.data.data.timestamp);
                            } else {
                                window.open("https://www.agop.com.cn/pc/views/qc/material_inspection/material_inspection_show.html?INSP_NO=" + row.qcNo + "&sign=" + res.data.data.sign + "&timestamp=" + res.data.data.timestamp);
                            }
                        }
                    })
                } else {
                    this.$message({
                        type: "error",
                        message: "请填写QC编号!"
                    });
                }

            },
            init() {
                supplierSelect().then(res => {
                    this.supplierDic = res.data.data;
                })
                unitSelect().then(res => {
                    this.packUnitDic = res.data.data;
                })
                getDictionary({ code: 'label_color' }).then(res => {
                    this.labelColorDic = res.data.data;
                });
                this.changeByInType();
            },
            checkNum(num, row) {
                row.inType = this.inType;
                if(this.inType === "其它入仓"||this.inType === "盘盈入仓"){
                    return;
                }
                overflowNum(row).then(res => {
                    if (parseInt(num) > parseInt(res.data.data)) {
                        row.num = res.data.data;
                        if(row.maxNum && row.maxNum > 0 && row.num && row.num > 0){
                            row.packCtnNum =Math.floor(row.num/row.maxNum)
                            row.packSpec = row.maxNum+"*"+row.packCtnNum;
                            let i = Math.floor(row.num%row.maxNum);
                            if(i> 0){
                                if(row.packCtnNum < 1) {
                                    row.packSpec = i + "*1";
                                } else {
                                    row.packSpec = row.maxNum+"*"+row.packCtnNum+ " + " + i + "*1";
                                }
                                row.packCtnNum = parseInt(row.packCtnNum)+1;
                            }
                        }else {
                            row.packSpec = "";
                            row.packCtnNum = "";
                        }
                        // if (row.price && row.num) {
                        //     row.totalPrice = row.price * row.num;
                        // }
                        this.updateFooterEvent();
                        this.$message({
                            type: "warning",
                            message: "数量不能大于["+row.num+"]!"
                        });
                    }
                })
            },
            handleSelectPackUnit(value) {
                console.log(value)
            },
            changeByFromNo(){
                const $table = this.$refs.tableRef;
                if($table.getTableData().fullData.length>0){
                    this.$message({
                        type: "warning",
                        message: "切换入仓类型或重新选择供应商会自动清空入仓项！"
                    });
                    $table.loadData([]);
                }
            },
            changeByInType() {
                const $table = this.$refs.tableRef;
                $table.showColumn("aboutNo");
                $table.showColumn("aboutItem");
                $table.showColumn("orderIdNo");
                $table.showColumn("deliAddr");
                if (this.inType === "生产入仓") {
                    this.tableHeader.aboutNoHeader = "生产编号";
                    this.tableHeader.aboutItemHeader = "生产项";
                    // this.$refs.tableRef.columns[13].editRender.enabled = false;
                    this.$refs.tableRef.columns[14].editRender.enabled = false;
                } else if (this.inType === "采购入仓") {
                    this.tableHeader.aboutNoHeader = "采购单号";
                    this.tableHeader.aboutItemHeader = "采购项";
                    $table.hideColumn("deliAddr");
                    this.$refs.tableRef.columns[13].editRender.enabled = false;
                    this.$refs.tableRef.columns[14].editRender.enabled = false;
                    $table.hideColumn("orderIdNo");
                } else if (this.inType === "退货入仓") {
                    if(this.isRole === 1) {
                        this.tableHeader.aboutNoHeader = "订单编号";
                        this.tableHeader.aboutItemHeader = "订货项";
                    }else if(this.isRole === 3){
                        this.tableHeader.aboutNoHeader = "生产编号";
                        this.tableHeader.aboutItemHeader = "生产项";
                    }
                    $table.hideColumn("deliAddr");
                    this.$refs.tableRef.columns[13].editRender.enabled = false;
                    this.$refs.tableRef.columns[14].editRender.enabled = false;
                    $table.hideColumn("orderIdNo");
                } else if (this.inType === "盘盈入仓") {
                    this.tableHeader.aboutNoHeader = "盘点单号";
                    this.tableHeader.aboutItemHeader = "货项";
                    $table.hideColumn("aboutNo");
                    $table.hideColumn("aboutItem");
                    $table.hideColumn("orderIdNo");
                    $table.hideColumn("deliAddr");
                    this.$refs.tableRef.columns[13].editRender.enabled = true;
                    this.$refs.tableRef.columns[14].editRender.enabled = true;
                } else if (this.inType === "其它入仓" || this.inType ==="调拨入仓") {
                    this.tableHeader.aboutNoHeader = "相关单号";
                    this.tableHeader.aboutItemHeader = "相关项";
                    $table.hideColumn("aboutNo");
                    $table.hideColumn("aboutItem");
                    $table.hideColumn("orderIdNo");
                    $table.hideColumn("deliAddr");
                    this.$refs.tableRef.columns[13].editRender.enabled = true;
                    this.$refs.tableRef.columns[14].editRender.enabled = true;
                }
                this.$emit("disabledFiled", false);
                $table.loadData([]);
            },
            setData(editable, idNo) {
                if (idNo) {
                    this.query.idNo = idNo
                    this.idNo = idNo
                }
                this.changeByInType();
                this.onLoad(this.page)
                this.editable = editable;
            },
            updateStatus(scope) {
                this.$refs.tableRef.updateStatus(scope);
            },
            calcSum(list, field) {
                let count = 0
                list.forEach(item => {
                    count += Number(item[field])
                })
                if (field == 'totalPrice') {
                    return this.$toFixed(count,2);
                } else {
                    return this.$toFixed(count,0);
                }
            },
            // 在值发生改变时更新表尾合计
            updateFooterEvent(params) {
                let xTable = this.$refs.tableRef
                xTable.updateFooter()
            },
            footerMethod(table) {
                console.log("table", table);
                return [
                    table.columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计'
                        }
                        if (['num', 'totalPrice','packCtnNum'].includes(column.field)) {
                            return this.calcSum(table.data, column.field)
                        }
                        return null
                    })
                ]
            },
            calTotalPrice(price, num, scope) {
                console.log("price", scope.row.maxNum);
                console.log("num", num);
                this.$refs.tableRef.updateStatus(scope);
                let row = scope.row;
                if(row.maxNum && row.maxNum > 0 && num && num > 0){
                    row.packCtnNum =Math.floor(num/row.maxNum)
                    row.packSpec = row.maxNum+"*"+row.packCtnNum;
                    let i = Math.floor(num%row.maxNum);
                    console.log('Math.floor(num%row.maxNum);',row);
                    if(i> 0){
                        if(row.packCtnNum < 1) {
                            row.packSpec = i + "*1";
                        } else {
                            row.packSpec = row.maxNum+"*"+row.packCtnNum+ " + " + i + "*1";
                        }
                        row.packCtnNum = parseInt(row.packCtnNum)+1;
                    }
                } else {
                    row.packSpec = "";
                    row.packCtnNum = "";
                }
                // if (price && num) {
                //     row.totalPrice = (price * num).toFixed(2);
                // }
            },
            calTotalNum(price,packCtnNum, scope) {
                console.log("packCtnNum", packCtnNum);
                this.$refs.tableRef.updateStatus(scope);
                let row = scope.row;
                if(row.maxNum && row.maxNum > 0 && packCtnNum && packCtnNum > 0 && row.num && row.num > 0){
                    row.num = packCtnNum*row.maxNum;
                    row.packSpec = row.maxNum+"*"+packCtnNum;
                }
                // if (price && row.num) {
                //     row.totalPrice = (price * row.num).toFixed(2);
                // }
            },
            refresh() {
                this.page = {
                    pageSize: 10,
                    currentPage: 1,
                }
                this.query = {}
                this.onLoad(this.page)
            },
            pageChange(e) {
                this.page = {
                    pageSize: e.pageSize,
                    currentPage: e.currentPage,
                }
                this.onLoad(this.page)
            },

            isActiveStatus(row) {
                const $table = this.$refs.tableRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            clearAll() {
                this.data = [];
                this.$refs.tableRef.remove();
            },
            async setProdItemList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                console.log(selectData)
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.aboutNo === item.tabNo && val.aboutItem === item.tabItem)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                aboutNo: item.tabNo,
                                aboutItem: item.tabItem,
                                barCode: item.barcode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: item.price,
                                maxNum: item.maxNum,
                                // packUnit: item.packUnit,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                // qcNo: item.qcNo,
                                inType: $this.inType,
                                orderIdNo:item.orderNo,
                                deliAddr:item.deliAddr,
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                console.log("mat.maxNum", mat.maxNum)
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                // mat.totalPrice = (mat.num * mat.price).toFixed(2);
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setPurchaseItemList(list){
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                console.log(selectData)
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                console.log("existsList",existsList)
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => (val.aboutNo === item.idNo && val.aboutItem.toString() === item.itemNo.toString()))) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                aboutNo: item.idNo,
                                aboutItem: item.itemNo,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: item.price,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                maxNum: item.maxNum,
                                inType: $this.inType,
                                deliAddr:item.deliAddr
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                console.log("mat.maxNum", mat.maxNum)
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                // mat.totalPrice = (mat.num * mat.price).toFixed(2);
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setOrderItemList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                console.log(selectData)
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => (val.aboutNo === item.idNo && val.aboutItem === item.itemNo))) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                aboutNo: item.idNo,
                                aboutItem: item.itemNo,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.materialType,
                                num: (item.num - item.deliNum).toFixed(0),
                                unit: item.unit,
                                price: item.price,
                                // totalPrice: ((item.num - item.deliNum) * item.price).toFixed(2),
                                // packUnit: item.packUnit,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                maxNum: item.maxNum,
                                packLabel: item.packLabelContent,
                                // qcNo: item.qcNo,
                                inType: $this.inType,
                                deliAddr:item.deliAddr
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                console.log("mat.maxNum", mat.maxNum)
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                // mat.totalPrice = (mat.num * mat.price).toFixed(2);
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setMaterial(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                console.log(selectData)
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!$table.getTableData().fullData.some((val) => (val.materialNo == item.materialNo))) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                barCode: item.barCode,
                                specification: item.specification,
                                num: 0,
                                unit: item.unit,
                                price: 0,
                                totalPrice: 0,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                packNum: item.packSize,
                                remark: item.remark,
                                inType: $this.inType,
                                maxNum: item.maxNum,
                                deliAddr: item.deliAddr,
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = res.data.data;
                                // mat.totalPrice = (mat.num * mat.price).toFixed(2);
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            handleAdd() {
                if (!this.inType) {
                    this.$message({
                        type: "error",
                        message: "请先选择入仓类型!"
                    });
                    return;
                }
                if (this.inType === "生产入仓") {
                    if (!this.fromDept|| !this.fromNo || !this.fromName) {
                        this.$message({
                            type: "error",
                            message: "请先选择加工商!"
                        });
                        return;
                    }
                  this.$refs.selectProdItemRef.setSearchType('supplier_in');
                    this.$refs.selectProdItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.fromDept,3);
                } else if (this.inType === "采购入仓") {
                    if (!this.fromDept|| !this.fromNo || !this.fromName) {
                        this.$message({
                            type: "error",
                            message: "请先选择供应商!"
                        });
                        return;
                    }
                    this.$refs.selectPurchaseItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.fromDept,1);
                } else if (this.inType === "退货入仓") {
                    if(this.isRole === 1){
                        if (!this.fromDept|| !this.fromNo || !this.fromName) {
                            this.$message({
                                type: "error",
                                message: "请先选择客户!"
                            });
                            return;
                        }
                        this.$refs.selectOrderItemRef.showSelect('stockIn',this.$refs.tableRef.getTableData().fullData, this.fromNo);
                    }else if(this.isRole === 3){
                        this.$refs.selectProdItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.toDept,1);
                    }
                } else if (this.inType === "盘盈入仓") {
                    this.$refs.selectMaterial.showSelect(this.$refs.tableRef.getTableData().fullData,'other_stock_in');
                } else if (this.inType === "其它入仓") {
                    this.$refs.selectMaterial.showSelect(this.$refs.tableRef.getTableData().fullData,'other_stock_in');
                }
            },
            contextMenuClickEvent(data) {
                const menu = data.menu;
                const row = data.row;
                const column = data.column;
                const $table = this.$refs.tableRef
                if ($table) {
                    switch (menu.code) {
                        case 'hideColumn':
                            $table.hideColumn(column)
                            break
                        case 'showAllColumn':
                            $table.resetColumn(true)
                            break
                        case 'copy':
                            // if (XEClipboard.copy(row[column.field])) {
                            //   ElMessage.success('保存成功')
                            // }
                            // ElMessage.success('复制成功')
                            break
                        case 'reload':
                            //  findList()
                            break
                        case 'insertAt':
                            $table.insertAt({}, row || -1).then(({row}) => {
                                $table.setEditCell(row, column || 'name')
                            })
                            break
                        case 'remove':
                            $table.remove(row)
                            break
                        case 'save':
                            // ElMessage.success('保存成功')
                            break
                    }
                }
            },
            disabledCommit(data) {
                this.$emit("disabledCommit", data);
            },
            editActivedEvent(row) {//激活单元格事件
                this.isEdit = true;
                this.disabledCommit(true);
            },
            editClosedEvent(row) {
                console.log(row)
                const $table = this.$refs.tableRef;
                $table.clearValidate();
                this.disabledCommit(false);
            },
            async handleSaveRow(row) {
                const err = await this.validEvent(row);
                if (err) {
                    return
                }

            },
            async validEvent(row) {
                const $table = this.$refs.tableRef
                const errMap = await $table.validate(row).catch(errMap => errMap)
                return errMap;

            },
            formatType(value) {
                let value2 = "";
                this.customerTypeList.forEach(res => {
                    if (value === res.dictKey) {
                        value2 = res.dictValue;
                    }
                });
                return value2
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            async handleDelete(row) {
                const $table = this.$refs.tableRef
                if (row.id) {
                    this.$confirm('是否确认删除?', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        if ($table.getTableData().fullData.length === 1) {
                            this.$emit("disabledFiled", false);
                        }
                        $table.remove(row)
                    }).then(() => {
                        this.$message({type: "success", message: "操作成功，保存后生效!"});
                    })
                } else {
                    if ($table.getTableData().fullData.length === 1) {
                        this.$emit("disabledFiled", false);
                    }
                    $table.remove(row)
                }
            },
            beforeEdit({row, rowIndex, column, columnIndex}) {
                if (this.editable) {

                }
                return this.editable;
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                if (this.$refs.crud) this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            formateDate(list) {
                list.forEach(item => {
                    // item.totalPrice = (item.num * item.price).toFixed(3);
                })
            },
            onLoad(page, params = {}) {
                this.query.idNo = this.idNo;
                if (this.$refs.tableRef.getInsertRecords().length > 0 || this.$refs.tableRef.getRemoveRecords().length > 0 ||
                    this.$refs.tableRef.getUpdateRecords().length > 0) {
                    this.$confirm("搜索会丢失本次新增/编辑/删除的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(() => {
                        this.loading = true;
                        console.log('aaaaaaaaaaaa', this.query)
                        findList(Object.assign(params, this.query)).then(res => {
                            const data = res.data.data;
                            // this.page.total = data.total;
                            this.list = data;
                            this.loading = false;
                            this.selectionClear();
                            this.isEdit = false;
                            this.formateDate(this.list);
                        });
                    })
                } else {
                    this.loading = true;
                    console.log('aaaaaaaaaaaa', this.query)
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        // this.page.total = data.total;
                        this.list = data;
                        this.loading = false;
                        this.selectionClear();
                        this.isEdit = false;
                        this.formateDate(this.list);
                    });
                }
            },

        }
    };
</script>

<style scoped>
    :deep(.vxe-pulldown.size--medium) {
        z-index: 99999 !important;
    }

    .vxe-table--tooltip-wrapper {
        z-index: 10000 !important;
    }

    :deep(.vxe-table--fixed-right-wrapper) {
        z-index: 99999 !important;
    }
</style>
